<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
     <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
     <el-breadcrumb-item>商品管理</el-breadcrumb-item>
     <el-breadcrumb-item>添加商品</el-breadcrumb-item>
     </el-breadcrumb>
     <el-card >
       <el-row>
         <el-col>
             <el-alert
               title="添加商品信息"
               type="info"
               center
               show-icon
               :closable='false'>
             </el-alert>
         </el-col>
       </el-row>
       <el-row>
         <el-col>
           <el-steps :space='200' :active="active - 0" finish-status="success" align-center>
           <el-step title="基本信息"></el-step>
           <el-step title="商品参数"></el-step>
           <el-step title="商品属性"></el-step>
           <el-step title="商品图片"></el-step>
           <el-step title="商品内容"></el-step>
           <el-step title="完成"></el-step>
         </el-steps>
         </el-col>
       </el-row>
       <el-row>
         <el-col>
            <el-form :model="addfrom" :rules="addfromrules" label-position='top' ref="addfromref" label-width="100px" class="demo-ruleForm">
           <el-tabs v-model='active' tab-position="left" :before-leave='beforeleave' @tab-click='tabClicked'>
            <el-tab-pane label="基本信息"  name='0'>
                  <el-form-item prop='goods_name' label='商品名称'>
                    <el-input v-model="addfrom.goods_name"></el-input>
                  </el-form-item>
                  <el-form-item prop='goods_price' label='商品价格'>
                    <el-input v-model="addfrom.goods_price"></el-input>
                  </el-form-item>
                  <el-form-item prop='goods_number' label='商品数量'>
                    <el-input v-model="addfrom.goods_number"></el-input>
                  </el-form-item>
                  <el-form-item prop='goods_weight' label='商品重量'>
                    <el-input v-model="addfrom.goods_weight"></el-input>
                  </el-form-item>
                  <el-form-item prop='goods_category' label='商品分类'>
                    <el-cascader
                     v-model="addfrom.goods_cat"
                    :options=" goodscategoryinfo"
                    :props="props"
                     @change="categorychange"></el-cascader>
                  </el-form-item>
            </el-tab-pane>
           <el-tab-pane label="商品参数"  name='1'>
              <el-form-item v-for="(item) in manyTabinfo" :key="item.attr_id" :label='item.attr_name'>
                    <el-checkbox-group v-model="item.attr_vals"   >
                        <el-checkbox border   v-for="(cb,i) in item.attr_vals" :key="i" :label='cb'></el-checkbox>
                    </el-checkbox-group>
              </el-form-item>
           </el-tab-pane>
           <el-tab-pane label="商品属性"  name='2'>
             <el-form-item  v-for="(item) in onlyTabinfo" :key="item.attr_id" :label='item.attr_name'>
               <el-input v-model="item.attr_vals" ></el-input>
             </el-form-item>
           </el-tab-pane>
           <el-tab-pane label="商品图片"  name='3'>
             <el-upload
                :action="upload"
               :on-preview="handlePreview"
               :on-remove="handleRemove"
               list-type="picture"
               :headers='headersObj'
               :on-success='onsuccess'>
             <el-button size="small" type="primary">点击上传</el-button>
           </el-upload>
           </el-tab-pane>
           <!-- 商品内容编辑框 -->
           <el-tab-pane label="商品内容"  name='4'>
              <quill-editor 
                  style="height:300px"
                   ref="myQuillEditor"
                   v-model="addfrom.goods_introduce"
               />       
               <el-button type='primary' @click="addgoodsfrom">添加商品</el-button>   
             </el-tab-pane>        
  </el-tabs>
   </el-form>
         </el-col>
       </el-row>
     </el-card>
     <!-- 浏览照片的弹窗 -->
     <el-dialog
       title="浏览"
       :visible.sync="uploadimgdiaolog"
       width="50%">
       <img class="img" :src='imgurl' alt="">
  <span slot="footer" class="dialog-footer">
    <el-button @click="uploadimgdiaolog = false">取 消</el-button>
    <el-button type="primary" @click="uploadimgdiaolog = false">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
 import  _  from 'lodash'
  export default {
    name:'add',
    data () {
      return {
        active:'0',
        addfrom:{
          goods_name:'',
          goods_price:'0',
          goods_number:'0',
          goods_weight:'0',
          goods_cat:[],
          pics:[],
          goods_introduce:'',
          attrs:[]
        },
        goodscategoryinfo:[],
        //动态参数数据
        manyTabinfo:[],
        //静态属性
        onlyTabinfo:[],  
        //照片发送网络请求设置请求头
        headersObj:{
          Authorization:window.sessionStorage.getItem('token')
        },
        //控制浏览图片窗显示或隐藏
        uploadimgdiaolog:false,
        //图片的url地址
        imgurl:'',
        props:{
            expandTrigger: 'hover',
            value:'cat_id',
            label:'cat_name',
            children:'children'
        },
        upload:'http://127.0.0.1:8888/api/private/v1/upload',
        addfromrules:{
         goods_name:[
             { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
         goods_price:[
            { required: true, message: '请输入商品价格', trigger: 'blur' }
         ],
         goods_number:[
             { required: true, message: '请输入商品数量', trigger: 'blur' } 
         ],
        goods_weight:[
             { required: true, message: '请输入商品重量', trigger: 'blur' } 
         ],
         goods_category:[
            { required: true, message: '请选择商品分类', trigger: 'blur' } 
         ]
        }
      }
    },
    computed: {
      cateId(){
        if(this.addfrom.goods_cat.length === 3){
          return this.addfrom.goods_cat[2]
        }
        return null
      }
    },
    created () {
      this.getgoodscategory()
    },
    methods: {
    //获取商品分类数据
     async getgoodscategory(){
         const result = await this.$http.get(`categories`)
         if(result.data.meta.status !=200){
           return  this.$message({showClose: true,message: `获取商品分类失败`,type: 'error'})
         }
         this.goodscategoryinfo=result.data.data
      },
    //联机选择框发生变化触发该方法
    categorychange(){
      console.log(this.addfrom.goods_cat)
    },
    beforeleave(activeName, oldActiveName){
      //离开的标签
      // console.log(oldActiveName)
      //即将进入的标签
      // console.log(activeName)
      if(oldActiveName ==='0' && this.addfrom.goods_cat.length !== 3){
         this.$message({showClose: true,message: `请选择商品分类的选择框`,type: 'error'})
        return false
      }
    },
    //点击复选框触发方法
    async tabClicked(){
      // console.log(this.active)
      if(this.active === '1'){
        let  result =await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel : 'many'}})
        if(result.data.meta.status !=200){
          return  this.$message({showClose: true,message: `获取商品分类失败`,type: 'error'})
        }
        result.data.data.forEach(item=>{
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
       this.manyTabinfo=result.data.data
    }
    if(this.active === '2'){
      let result = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel : 'only'}})
       if(result.data.meta.status !=200){
          return  this.$message({showClose: true,message: `获取商品分类失败`,type: 'error'})
        }
      console.log(result)
      this.onlyTabinfo=result.data.data
    }
    if(this.active === '3'){
        
    }
    },
    //浏览照片触发该事件
    handlePreview(file){
     this.imgurl=file.response.data.url
     this.uploadimgdiaolog=true

    },
    //删除照片触发该事件
    handleRemove(file){
      const tmp_path =file.response.data.tmp_path
    const i = this.addfrom.pics.filter(item=>{
      return  item.pic !==tmp_path
      })
      //过滤出数据符合条件的元素
      this.addfrom.pics = i
    },
    //文件上传成功时的钩子
    onsuccess(response){
      console.log(response)
      if(response.meta.status !=200 ){
        return this.$message({showClose: true,message: `上传图片失败`,type: 'error'})
      }
      const picobj={'pic':response.data.tmp_path}
      this.addfrom.pics.push(picobj)
      console.log(this.addfrom)
    },
    //添加商品表单
    async addgoodsfrom(){
      // const validate =await this.$refs.addfromref.validate()
      // if(!validate) { return  this.$message({showClose: true,message: `请填写必要项`,type: 'error'}) }
      // 进行深拷贝
      const form = _.cloneDeep(this.addfrom)
      //编辑商品分类
      form.goods_cat=form.goods_cat.join(',') 
      //编辑动态参数数据
       this.manyTabinfo.forEach(item=>{
         const manyobj={
           attr_id:item.attr_id,
           attr_value:item.attr_vals.join(' ')
           }
         this.addfrom.attrs.push(manyobj)
       })
      //编辑静态属性数据
       this.onlyTabinfo.forEach(item=>{
         const onlyobj={attr_id:item.attr_id,attr_value:item.attr_vals}
         this.addfrom.attrs.push(onlyobj)
       })
       form.attrs =this.addfrom.attrs
       //添加商品请求
       const result =  await this.$http.post('goods',form)
       console.log(result)
       if(result.data.meta.status != 201){
         return this.$message({showClose: true,message: `添加商品失败`,type: 'error'})
       }
       this.$message({showClose: true,message: `添加商品成功！`,type: 'success'})
       this.$router.push('/goods')
    }
    }
  }
</script>

<style lang="less" scoped>
.el-card{
  margin-top: 10px;
  height: 900px;
}
.el-steps{
  margin-top: 10px;
}
.el-tabs{
   margin-top: 10px;
}
.el-checkbox{
  margin: 0 10px 0 0 !important;
}
.img{
  width: 100%;
}
.el-button{
  margin-top: 100px;
}
</style>